import Vue from 'vue'

function delay_factory (ajax, delay = 300) {
  return async function (...arg) {
    let body = {}
    if (this.ajax_delay_once) {
      body = await ajax.apply(this, arg)
    } else {
      body = (await Promise.all([ajax.apply(this, arg), sleep(delay)]))[0]
      this.ajax_delay_once = true
    }
    return body
  }
}

const loadding_factory = function (ajax) {
  return async function (...arg) {
    Vue.$vux.loading.show({text: '加载中'})
    try {
      return await ajax.apply(this, arg)
    } finally {
      Vue.$vux.loading.hide()
    }
  }
}

const status_factory = function (ajax) {
  return async function (url, data, name = 'loadStatus') {
    this[name] = null // 加载中
    try {
      const result = await ajax.call(this, url, data)
      this[name] = true // 加载成功
      return result
    } finally {
      this[name] = false // 出错或加载失败
    }
  }
}

export {
  loadding_factory,
  delay_factory,
  status_factory
}